package i18nit

import grails.testing.mixin.integration.Integration
import grails.transaction.Rollback
import org.grails.web.servlet.mvc.GrailsWebRequest
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.MessageSource
import org.springframework.context.support.ResourceBundleMessageSource
import org.springframework.mock.web.MockHttpServletRequest
import org.springframework.mock.web.MockHttpServletResponse
import org.springframework.web.context.WebApplicationContext
import spock.lang.Shared
import spock.lang.Specification

@Integration
@Rollback
class CompanyControllerSpec extends Specification {

    @Autowired
    WebApplicationContext ctx

    @Autowired
    MessageSource messageSource

    @Shared
    GrailsWebRequest webRequest

    def setupSpec() {
//        URL url = new File('grails-app/i18n').toURI().toURL()
//        messageSource = new ResourceBundleMessageSource()
//        messageSource.bundleClassLoader = new URLClassLoader(url)
//        messageSource.basename = 'messages'
//        println "[setupSpec]" + messageSource.getMessage("default.blank.message", [1, 2] as Object[], "xxxxx", Locale.ENGLISH)
    }

    def setup() {
//        java.util.Locale.setDefault(Locale.ENGLISH)
        webRequest = grails.util.GrailsWebMockUtil.bindMockWebRequest(ctx)
    }

    def cleanup() {
        org.springframework.web.context.request.RequestContextHolder.resetRequestAttributes()
    }

    void "test something"() {
        given:
        def inst = new Company()
        def controller = new CompanyController()
        controller.messageSource = messageSource

        when:
        webRequest.request.method = "POST"
        controller.save(inst)
        println "[test case1]" + java.util.Locale.getDefault(Locale.Category.FORMAT)
        println "[test case1]" + controller.request.locales.collect { it }.join("/")
        println "[test case1]" + webRequest.request.locales.collect { it }.join("/")
        inst.errors.allErrors.each {
            println "[test case]" + messageSource.getMessage(it, Locale.ENGLISH)
        }

        then:
        webRequest.currentResponse.status == 422

        when:
        def errors = (webRequest.currentResponse as MockHttpServletResponse).getContentAsString()

        then:
        errors.contains("域的属性")
        errors.contains("不能为null")
    }
}
